﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestReadBinary
{
    class Program
    {
        static void Main(string[] args)
        {
            // <add name="EOCS" connectionString="Data Source=KLDB3\SQL2008;Initial Catalog=CDMS_UAT;Persist Security Info=True;User ID=CDMS_UAT_user;Password=Xh57887266;MultipleActiveResultSets=True;Application Name=e-Overtime;Workstation ID=AN2594" providerName="System.Data.SqlClient"/>
            using (SqlConnection connection = new SqlConnection(@"Data Source=KLSMARK\SQL2008;Initial Catalog=POSE_UAT;Persist Security Info=True;User ID=pose_uat_user;Password=Ma546225;"))
            {
                SqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT top 5 * FROM POPREVIEW where PO_NUMBER = '2181000004'";

                connection.Open();

                SqlDataReader dr = cmd.ExecuteReader();

                string fileName = string.Empty;
                byte[] fileBytes = null;

                if (dr.HasRows && dr.Read())
                {

                    fileName = (string)dr["PO_NUMBER"];
                    fileBytes = (byte[])dr["FILEDATA"];

                    using (FileStream fs = new FileStream(Path.Combine("C:\\temp\\saptest_2.pdf"), FileMode.OpenOrCreate))
                    {
                        fs.Write(fileBytes, 0, fileBytes.Length);
                        fs.Flush();
                    }
                }
            }
        }
    }
}
